package cn.donting.jme.swing.tab.scene.treenode;

import cn.donting.jme.EditorContent;
import cn.donting.jme.editor.scene.Scene;
import cn.donting.jme.editor.scene.SceneCamera;
import cn.donting.jme.event.SelectEvent;
import cn.donting.jme.event.light.SelectLightEvent;
import cn.donting.jme.expansion.builder.light.LightAttributeBuilder;
import cn.donting.jme.swing.tab.scene.SceneTreeTab;
import cn.donting.jme.utile.IconUtil;
import com.jme3.light.Light;
import com.jme3.scene.Spatial;
import lombok.Getter;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

@Getter
public class LightTreeNode extends SceneTreeNode {
    private JTree jTree;
    private Spatial spatial;
    private Light light;
    private JPopupMenu jPopupMenu;

    public LightTreeNode(JTree jTree, Light light,Spatial spatial) {
        this.jTree = jTree;
        this.spatial = spatial;
        this.light = light;
        EditorContent.setObjectData(light, SceneTreeTab.TREE_NODE_DATA_KEY, this);
    }

    @Override
    public String toString() {
        return light.getName();
    }

    public void openMenu(MouseEvent mouseEvent) {
        if (jPopupMenu != null) {
            jPopupMenu.show(jTree, mouseEvent.getX(), mouseEvent.getY());
            return;
        }
        jPopupMenu = new JPopupMenu();

    }

    @Override
    public SelectEvent getSelectEvent(){
        return new SelectLightEvent(jTree,light);
    }

    private DefaultTreeModel getTreeModel() {
        return (DefaultTreeModel) jTree.getModel();
    }


    public static LightTreeNode createTreeNode(JTree jTree,Light light, Spatial spatial) {
        LightTreeNode cameraTreeNode = new LightTreeNode(jTree, light, spatial);
        return cameraTreeNode;
    }

    @Override
    public Icon getIcon(int size) {
        List<LightAttributeBuilder> lightAttributeBuilders = EditorContent.getIocContainer().getBeansByTypes(LightAttributeBuilder.class);
        for (LightAttributeBuilder lightAttributeBuilder : lightAttributeBuilders) {
            if (lightAttributeBuilder.isHandle(light)) {
                if(light.isEnabled()){
                    return lightAttributeBuilder.getActiveIcon(size);
                }
                return lightAttributeBuilder.getIcon(size);
            }
        }
        return null;
    }

    @Override
    public String getName() {
        String name = light.getName();
        String objectId = EditorContent.getObjectId(light);
        if (name==null) {
            return "-"+objectId;
        }
        return light.getName()+objectId;
    }
}